import 'dart:async';
import 'package:flutter/material.dart';
import 'package:shadcn_ui/shadcn_ui.dart';
import 'package:animated_tree_view/animated_tree_view.dart' as treeview;
import 'package:yuellyfactory/components/NoScrollbarBehavior.dart';
import 'package:yuellyfactory/eventbus/EventBusUtil.dart';
import 'package:yuellyfactory/eventbus/EventRefreshBase.dart';
import 'package:yuellyfactory/eventbus/EventRefreshTree.dart';
import 'package:yuellyfactory/util/AuthUtil.dart';
import 'package:yuellyfactory/util/BaseRequest.dart';
import 'package:yuellyfactory/util/ColorUtil.dart';
import 'package:yuellyfactory/util/GlobalData.dart';
import 'package:yuellyfactory/util/ToastUtil.dart';
import 'package:yuellyfactory/util/ViewUtil.dart';
import 'package:yuellyfactory/views/Controller/PartController.dart';
import 'package:yuellyfactory/views/base/EditBrandVC.dart';
import 'package:yuellyfactory/views/base/MaterialEditVC.dart';
import 'package:yuellyfactory/views/base/MaterialVC.dart';
import 'package:yuellyfactory/views/base/TypeView.dart';
import 'package:yuellyfactory/views/dto/PricePart.dart';

import '../Controller/MaterialController.dart';
import '../dto/PopupAction.dart';
import '../dto/PriceSerial.dart';
import 'EditSerialVC.dart';
import 'MaterialAddVC.dart';
class BaseVC extends StatefulWidget {
  const BaseVC({super.key});

  @override
  State<BaseVC> createState() => _BaseVCState();
}

class _BaseVCState extends State<BaseVC> {

  late treeview.AutoScrollController _scrollController;
  treeview.TreeViewController? _controller;
  final formKey = GlobalKey<ShadFormState>();
  final dialogKey = GlobalKey<ShadFormState>();
  var currentSelect="";
  String currentType="";
  PricePart selectPricePart= PricePart();
  StreamSubscription? streamSubscription;
  StreamSubscription? treeStreamSubscription;
  PartController pricePartController=PartController();
  MaterialController materialController=MaterialController();
  List allDatas=[];
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _scrollController = treeview.AutoScrollController();
    getAllData();

    streamSubscription=eventBus.on<EventRefreshBase>().listen((event){

      getAllData();
    });
    treeStreamSubscription=eventBus.on<EventRefreshTree>().listen((event){
      if(event.id.isNotEmpty){
        currentSelect=event.id;
        selectPartById(currentSelect);
        if(currentType!="part"){
          treeview.ListenableNode node=sampleTree.elementAt(selectPricePart.path);
          _expandNodes(node as treeview.TreeNode,true);
        }
        setState(() {

        });
        if(currentType!="part"){
          pricePartController.refreshPricePart!(selectPricePart);
        }else{
          materialController.refreshPricePart!(selectPricePart);
        }


      }

    });
  }

  void _expandNodes(
  treeview.TreeNode preselectedNode,
         bool directionRootToNode) {
    final String path = preselectedNode.path;
    // example path: 623c79a5-3ae9-4706-bad0-7dd8093f3d1b.01JQPXYM0EMS9CMMRHM84Y9RZK.01JQPXYM0EJE7RHGMYV2V92CR3

    // Split the path by the dot separator to get individual node IDs
    final List<String> nodeIds = path.split(".");

    if (nodeIds.length >= 2) {
      // Generate all the paths from shortest (root) to longest (preselected node's parent)
      List<String> pathsToExpand = [];

      // Build all possible paths from root to the target node (excluding the target itself)
      for (int i = 1; i < nodeIds.length; i++) {
        // Creating paths of increasing length, starting from the root
        String currentPath = nodeIds[0];
        for (int j = 1; j < i; j++) {
          currentPath = "$currentPath.${nodeIds[j]}";
        }
        pathsToExpand.add(currentPath);
      }

      // If we're expanding from root to node, use the paths as they are (top-down)
      // If expanding from node to root, reverse the order (bottom-up)
      if (!directionRootToNode) {
        // Reverse the list to go from bottom up (nearest ancestor first)
        pathsToExpand = pathsToExpand.reversed.toList();
      }

      // Now expand the nodes in the appropriate order based on directionRootToNode
      for (final String nodePath in pathsToExpand) {
        final currentNode = _controller!.elementAt(nodePath);
        _controller!.expandNode(currentNode);
      }
    }
  }


  selectPartById(String id){
    for(PricePart type in allDatas){
      if(id==type.id){
        currentType="type";
        selectPricePart=type;
        break;
      }
      for(PricePart brand in type.materialList){
        if(brand.id==id){
          currentType="brand";
          selectPricePart=brand;
          break;
        }

        for(PricePart serial in brand.materialList){
          if(serial.id==id){
            currentType="serial";
            selectPricePart=serial;
            break;
          }
          for(PricePart part in serial.materialList){
            if(part.id==id){
              currentType="part";
              selectPricePart=part;
              break;
            }
          }
        }

      }

    }
  }

  @override
  void dispose() {
    if(streamSubscription!=null) {
      streamSubscription!.cancel();
    }
    if(treeStreamSubscription!=null) {
      treeStreamSubscription!.cancel();
    }
    super.dispose();
  }

  var sampleTree = treeview.TreeNode.root();

  @override
  Widget build(BuildContext context) {
    final theme = ShadTheme.of(context);
    return

      Container(
      child: DecoratedBox(
        decoration: BoxDecoration(
          borderRadius: theme.radius,
          border: Border.all(
            color: theme.colorScheme.border,
          ),
        ),
        child: ClipRRect(
          borderRadius: theme.radius,
          child: ShadResizablePanelGroup(
            children: [
              ShadResizablePanel(
                defaultSize: .2,
                minSize: .1,
                maxSize: .5,
                child:
                Card(
                  color: Colors.white,
                  child:Column(

                    mainAxisSize: MainAxisSize.min,
                    children: [
                      SizedBox(height: ViewUtil.screenHeight(10),),

                      Row(
                        children: [
                          SizedBox(width: ViewUtil.screenWidth(10),),
                          Text('基础物料',style: TextStyle(color: Colors.black,  fontSize: ViewUtil.fontSize(22),fontWeight: FontWeight.bold),),
                          Expanded(child: Container(),),
                          AuthUtil.instance.getMenuBtnWidget(AuthUtil.Base_Type_Create,
                              ViewUtil.addIcon("新增类型", (){
                                addType();
                              }))

                        ],

                      ),

                     // SizedBox(height: ViewUtil.screenHeight(10),),
                      Expanded(child:
                      treeview.TreeView.simple(
                          showRootNode: false,
                          scrollController: _scrollController,
                          focusToNewNode: false,
                          padding: EdgeInsets.symmetric(vertical: 0),
                          expansionIndicatorBuilder: (context, node) {
                            return treeview.ChevronIndicator.rightDown(
                              tree: node,
                              alignment: Alignment.centerRight,
                              //color: Colors.grey[700],
                              color:ColorUtil.colorBlue
                            );
                          },
                          indentation: const treeview.Indentation(
                              style: treeview.IndentStyle.roundJoint),
                          onItemTap: (item) {
                            print("Item tapped: ${item.key}");
                            currentSelect=item.key;
                            currentType=item.data.type;
                            selectPricePart=item.data;
                            setState(() {
                            });
                            if(currentType!="part"){
                              pricePartController.refreshPricePart!(selectPricePart);
                            }else{
                              materialController.refreshPricePart!(selectPricePart);
                            }
                          },
                          onTreeReady: (controller) {
                            _controller = controller;
                          },

                          builder: (context, node) =>  Container(

                            padding: EdgeInsets.symmetric(vertical: 0),
                            margin: EdgeInsets.symmetric(vertical: 0),
                            decoration: BoxDecoration(
                              color: currentSelect==node.key ? Colors.blue.withOpacity(0.1) : null,
                              borderRadius: BorderRadius.circular(4),
                            ),
                            child:Row(
                              children: [
                                SizedBox(width: 10,),
                                Expanded(child: Text("${node.data.name}",style: TextStyle(
                                    color: node.data.showInput==0?Colors.black:Colors.red,
                                    fontSize: ViewUtil.fontSize(22)),)),
                                Column(
                                  children: [
                                   // if(node.data.parentId=='0')
                                      ViewUtil.upIcon("向上排序", (){
                                        goUp(node.data,node);
                                      }),
                                  //  if(node.data.parentId=='0')
                                      ViewUtil.downIcon("向下排序", (){
                                        goDown(node.data,node);
                                      }),
                                  ],
                                ),

                                if(node.data.type=='part')
                                  SizedBox(width: 13,),
                                if(node.data.type!='part')
                                  SizedBox(width: 40,child:
                                  PopupMenuButton<int>(
                                    color: Colors.white,
                                    tooltip: '',
                                    // 三点按钮的图标
                                    icon: const Icon(Icons.more_vert,color: Colors.grey,),
                                    // 下拉菜单的位置
                                    offset: const Offset(0, 50),
                                    itemBuilder: (context) => _buildPopupMenuItems(node.data),
                                    // 点击菜单项的回调
                                    onSelected: (value) {
                                      debugPrint(value.toString());
                                      switch (value) {
                                        case 1:{//编辑分类
                                          editType(node.data);
                                          break;
                                        }

                                        case 2:{//删除分类
                                          showDelPart(node.data);
                                          break;
                                        }
                                        case 3:{//新增品牌
                                          // addBrand(node.data);

                                          PricePart partData=PricePart();
                                          partData.parentId=node.data.id;
                                          showShadSheet(
                                            side: ShadSheetSide.right,
                                            context: context,
                                            builder: (context) => EditBrandVC(callback: (){}, pricePart: partData)

                                            ,
                                          );
                                          break;


                                          break;
                                        }
                                        case 4:{//删除品牌
                                          showDelPart(node.data);
                                          break;
                                        }

                                        case 5:{//新增系列

                                          PricePart partData=PricePart();
                                          partData.parentId=node.data.id;
                                          showShadSheet(
                                            side: ShadSheetSide.right,
                                            context: context,
                                            builder: (context) => EditSerialVC(callback: (){}, pricePart: partData)

                                            ,
                                          );
                                          break;
                                        }
                                        case 6:{//删除系列
                                          showDelSerial(node.data);
                                          break;
                                        }
                                        case 7:{//新增型号

                                          PricePart partData=PricePart();
                                          partData.serialId=node.data.id;
                                          partData.parentId=node.data.parentId;
                                          partData.typeId=node.data.typeId;
                                          showShadSheet(
                                            side: ShadSheetSide.right,
                                            context: context,
                                            builder: (context) =>  MaterialEditVC(pricePart: partData, callback: () {
                                              //回调

                                            },),
                                          );
                                          break;
                                        }

                                      }
                                    },
                                  ),),

                                SizedBox(width: 15,)
                              ],
                            ),

                            // ListTile(
                            //
                            //   title: Row(
                            //     children: [
                            //       Expanded(child: Text("${node.data.name}",style: TextStyle(
                            //           color: node.data.showInput==0?Colors.black:Colors.red,
                            //           fontSize: ViewUtil.fontSize(22)),)),
                            //       Text('12321')
                            //     ],
                            //   ),
                            //   trailing:
                            //   node.data.type=='part'?null:PopupMenuButton<int>(
                            //     color: Colors.white,
                            //     tooltip: '',
                            //     // 三点按钮的图标
                            //     icon: const Icon(Icons.more_vert,color: Colors.grey,),
                            //     // 下拉菜单的位置
                            //     offset: const Offset(0, 50),
                            //     itemBuilder: (context) => _buildPopupMenuItems(node.data),
                            //     // 点击菜单项的回调
                            //     onSelected: (value) {
                            //       debugPrint(value.toString());
                            //       switch (value) {
                            //         case 1:{//编辑分类
                            //           editType(node.data);
                            //           break;
                            //         }
                            //
                            //         case 2:{//删除分类
                            //           showDelPart(node.data);
                            //           break;
                            //         }
                            //         case 3:{//新增品牌
                            //          // addBrand(node.data);
                            //
                            //           PricePart partData=PricePart();
                            //           partData.parentId=node.data.id;
                            //           showShadSheet(
                            //             side: ShadSheetSide.right,
                            //             context: context,
                            //             builder: (context) => EditBrandVC(callback: (){}, pricePart: partData)
                            //
                            //             ,
                            //           );
                            //           break;
                            //
                            //
                            //           break;
                            //         }
                            //         case 4:{//删除品牌
                            //           showDelPart(node.data);
                            //           break;
                            //         }
                            //
                            //         case 5:{//新增系列
                            //
                            //           PricePart partData=PricePart();
                            //           partData.parentId=node.data.id;
                            //           showShadSheet(
                            //             side: ShadSheetSide.right,
                            //             context: context,
                            //             builder: (context) => EditSerialVC(callback: (){}, pricePart: partData)
                            //
                            //             ,
                            //           );
                            //           break;
                            //         }
                            //         case 6:{//删除系列
                            //           showDelSerial(node.data);
                            //           break;
                            //         }
                            //         case 7:{//新增型号
                            //
                            //           PricePart partData=PricePart();
                            //           partData.serialId=node.data.id;
                            //           partData.parentId=node.data.parentId;
                            //           partData.typeId=node.data.typeId;
                            //           showShadSheet(
                            //             side: ShadSheetSide.right,
                            //             context: context,
                            //             builder: (context) =>  MaterialEditVC(pricePart: partData, callback: () {
                            //               //回调
                            //
                            //             },),
                            //           );
                            //           break;
                            //         }
                            //
                            //       }
                            //     },
                            //   ),
                            // ),
                          ),
                          tree: sampleTree),)

                    ],
                  )

                ),
              ),
              ShadResizablePanel(

                defaultSize: .8,
                child:

                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [

                    // Card( color: Colors.white,
                    //   child: Padding(
                    //     padding: const EdgeInsets.all(5.0),
                    //     child: Row(
                    //       children: [
                    //         SizedBox(width: ViewUtil.screenWidth(10),),
                    //         ViewUtil.textButton('新增分类', 20, 15, ViewUtil.radio(15),
                    //             ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(20), (){
                    //               addType();
                    //
                    //             }),
                    //         SizedBox(width: ViewUtil.screenWidth(10),),
                    //         Visibility(
                    //             visible: currentType==0,
                    //             child: ViewUtil.textButton('新增型号', 20, 15, ViewUtil.radio(15),
                    //                 ColorUtil.colorBlue, ColorUtil.colorBlue, Colors.white , ViewUtil.fontSize(20), (){
                    //                   addMaterial();
                    //
                    //                 }))
                    //         ,
                    //       ],
                    //     ),
                    //   ),
                    // ),
                    Expanded(
                      child: Card( color: Colors.white,
                        child:
                        ScrollConfiguration(
                          behavior: NoScrollbarBehavior(),
                          child: SingleChildScrollView(
                            child:
                            Padding(
                              padding: const EdgeInsets.all(5.0),
                              child:
                                  Column(
                                    children: [
                                      Visibility(
                                          visible: currentSelect.isEmpty,
                                          child: Container()),
                                      Visibility(
                                          visible: currentType!="part",
                                          maintainState: true,
                                          child: TypeView(partController:pricePartController ,)),
                                      Visibility(
                                          visible: currentType=="part",
                                          maintainState: true,
                                          child:  MaterialVC(partController:materialController ,)),
                                    ],
                                  )


                              ,
                            ),),
                        ),

                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }


  // 动态构建菜单项的方法
  List<PopupMenuItem<int>> _buildPopupMenuItems(PricePart partData) {
    selectPricePart=partData;
    currentSelect=partData.id;
    currentType=selectPricePart.type;
    setState(() {

    });
    // 这里可以根据实际需求动态生成菜单项列表
    // 示例：从数据源获取或根据条件生成
    final List<PopupAction> actions = [

      if(partData.type=='type'&&AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Type_Create))

        PopupAction(
          value: 1,
          label: "编辑分类",

        ),

      if(partData.type=='type'&&AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Type_Delete))

      PopupAction(
        value: 2,
        label: "删除分类",

      ),
      // 可以根据条件动态添加菜单项
      if(partData.type=='type'&&AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Brand_Create))
      PopupAction(
        value: 3,
        label: "新增品牌",

      ),
      if(partData.type=='brand'&&AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Brand_Delete))
        PopupAction(
          value: 4,
          label: "删除品牌",
        ),
      if(partData.type=='brand'&&AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Serial_Create))
        PopupAction(
          value: 5,
          label: "新增系列",
        ),
      if(partData.type=='serial'&&AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Serial_Delete))
        PopupAction(
          value: 6,
          label: "删除系列",
        ),
      if(partData.type=='serial'&&AuthUtil.instance.checkMenuBtn(AuthUtil.Base_Material_Create))
        PopupAction(
          value: 7,
          label: "新增型号",
        ),
    ];

    return actions.map((action) {
      return PopupMenuItem<int>(
        value: action.value,
        child: Row(
          children: [

            const SizedBox(width: 8),
            Text(action.label),
          ],
        ),
      );
    }).toList();
  }


  void addType(){
    List options=["1","2","3","4","5"];

    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
          actions: [ShadButton(child: Text('确定'),onPressed: (){
            submitPart();
          },)],
          child:



          ShadForm(
            key: dialogKey,
            child: Column(
              children: [
                ShadInputFormField(
                  id: 'name',
                  label: const Text('分类名称'),
                  placeholder: const Text('请输入分类名称'),
                  validator: (v) {
                    if (v.isEmpty) {
                      return '请输入分类名称';
                    }
                    return null;
                  },
                ),
                ShadSelectFormField<String>(
                  id: 'level',
                  label: const Text('分类级别(数字越小级别越高)'),
                  minWidth: 800,
                  initialValue: null,
                  options: options.map((item) {
                    final value = item.isNotEmpty ? item : '';
                    return ShadOption<String>(
                      value: value,
                      child: Text(value),
                    );
                  }).toList(),
                  selectedOptionBuilder: (context, value) {
                    // 处理value可能为null的情况
                    if (value == null || value.isEmpty || value == 'none') {
                      return const Text('请选择');
                    }
                    return Text(value);
                  },
                  placeholder: const Text('请选择'),
                  validator: (v) {
                    if (v == null) {
                      return '请选择';
                    }
                    return null;
                  },
                ),
              ],
            ),)

        )
    );
  }
  void editType(PricePart partData){
    List options=["1","2","3","4","5"];
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitType(partData);
            },)],
            child:
            ShadForm(
              key: formKey,
              child: Column(
                children: [
                  ShadInputFormField(
                    id: 'name',
                    label: const Text('分类名称'),
                    placeholder: const Text('请输入分类名称'),
                    initialValue: partData.name,
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入分类名称';
                      }
                      return null;
                    },
                  ),
                  ShadSelectFormField<String>(
                    id: 'level',
                    label: const Text('分类级别(数字越小级别越高)'),
                    minWidth: 800,
                    initialValue: partData.level.isEmpty?null:partData.level,
                    options: options.map((item) {
                      final value = item.isNotEmpty ? item : '';
                      return ShadOption<String>(
                        value: value,
                        child: Text(value),
                      );
                    }).toList(),
                    selectedOptionBuilder: (context, value) {
                      // 处理value可能为null的情况
                      if (value == null || value.isEmpty || value == 'none') {
                        return const Text('请选择');
                      }
                      return Text(value);
                    },
                    placeholder: const Text('请选择'),
                    validator: (v) {
                      if (v == null) {
                        return '请选择';
                      }
                      return null;
                    },
                  ),
                ],
              ),)

        )
    );
  }


  void addBrand(PricePart partData){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(
            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitBrand(partData);
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: ShadInputFormField(
                id: 'name',
                label: const Text('品牌名称'),
                placeholder: const Text('请输入品牌名称'),
                validator: (v) {
                  if (v.isEmpty) {
                    return '请输入品牌名称';
                  }
                  return null;
                },
              ),)

        )
    );
  }

  void submitBrand(PricePart priceData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values= dialogKey.currentState!.value;
      var name=values["name"];
      var parm={
        "name":name,
        "parentId":priceData.id
      };
      BaseRequest.postHttp("price/editpart",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("添加成功");
          getAllData();
          Navigator.pop(context);
        }
      }, onError: (error){

      });
    }
  }


  // void addBrandType(PricePart partData){
  //   showShadSheet(
  //     side: ShadSheetSide.right,
  //     context: context,
  //     builder: (context) =>  MaterialAddVC(pricePart:partData , callback: () {
  //       //回调
  //     },),
  //   );
  // }

  void addMaterial(){
    showShadDialog(context: context, builder: (context)=>
        ShadDialog(

            actions: [ShadButton(child: const Text('确定'),onPressed: (){
              submitMaterial();
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: [
                  ShadInputFormField(
                    id: 'name',
                    label: const Text('型号名称'),
                    placeholder: const Text('请输入型号名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入型号名称';
                      }
                      return null;
                    },
                  ),
                  const SizedBox(height: 16),
                  ShadInputFormField(
                    id: 'code',
                    label: const Text('Code'),
                    placeholder: const Text('请输入Code'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入Code';
                      }
                      return null;
                    },
                  ),const SizedBox(height: 16),
                  ShadInputFormField(
                    id: 'spec',
                    label: const Text('型号说明'),
                    placeholder: const Text('请输入型号说明'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入型号说明';
                      }
                      return null;
                    },
                  ),

                ],
              )

              ,)

        )
    );
  }

  void submitMaterial(){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values= dialogKey.currentState!.value;
      var name=values["name"];
      var code=values["code"];
      var spec=values["spec"];
      var parentId="";
      if(selectPricePart.parentId=='0'){
        parentId=selectPricePart.id;
      }else{
        parentId=selectPricePart.parentId;
      }
      var parm={
        "name":name,
        "code":code,
        "spec":spec,
        "parentId":parentId,
      };
      BaseRequest.postHttp("price/editmatterial",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("添加成功");
          getAllData();
          Navigator.pop(context);
        }
      }, onError: (error){

      });
    }
  }

  void uploadDelPart(PricePart partData){
    var parm={
      "id":partData.id,

    };
    BaseRequest.postHttp("price/delpricemodel",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        getAllData();
        Navigator.of(context).pop(false);
      }
    }, onError: (error){

    });
  }


  void submitPart(){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values= dialogKey.currentState!.value;
      var name=values["name"];
      var level=values["level"];
      var parm={
        "name":name,
        "level":level,
      };
      BaseRequest.postHttp("price/editpart",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("添加成功");
          getAllData();
          Navigator.pop(context);
        }
      }, onError: (error){

      });



    }
  }

  void submitType(PricePart partData){
    if (formKey.currentState!.saveAndValidate()) {
      var values= formKey.currentState!.value;
      var name=values["name"];
      var level=values["level"];
      var parm={
        "name":name,
        "level":level,
        "id":partData.id
      };
      BaseRequest.postHttp("price/editpart",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });



    }
  }

  void goDown(PricePart partData,treeview.TreeNode node){
    var parm={
      "type":partData.type,
      "parentId":partData.parentId,
      "id":partData.id
    };
    BaseRequest.postHttp("price/downPart",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("操作成功");

        getAllData();
      }
    }, onError: (error){

    });
  }

  void goUp(PricePart partData,treeview.TreeNode node){
    var parm={
      "type":partData.type,
      "parentId":partData.parentId,
      "id":partData.id
    };
    BaseRequest.postHttp("price/upPart",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("操作成功");
        getAllData();

      }
    }, onError: (error){

    });
  }

  void getAllData(){
    BaseRequest.postHttp("price/baselist",parameters: {}, canTip: false , context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        dynamic datas=data["data"];
        List allParts=[];
        for(var i=0;i<datas.length;i++){
          var item=datas[i];
          var part=PricePart.fromJson(item);
          allParts.add(part);
        }
        allDatas=allParts;
        GlobalData.baseData=allDatas;
        initTreeDatas(allParts);
      }


    }, onError: (error){

    });
  }






  void initTreeDatas(List allParts){


    var trees=treeview.TreeNode.root();
    for(PricePart part in allParts){
      if(currentSelect==''){
        currentSelect=part.id;
        currentType=part.type;
        selectPricePart=part;
      }else{
        if(currentSelect==part.id){
          selectPricePart=part;
          currentType=selectPricePart.type;

        }
      }
      part.path=part.id;
      treeview.TreeNode node= treeview.TreeNode(key: part.id,data:part);
      for(PricePart brand in part.materialList){
        if(currentSelect==brand.id){
          selectPricePart=brand;
          currentType=selectPricePart.type;
        }
        brand.path="${part.id}.${brand.id}";
        treeview.TreeNode brandNode=treeview.TreeNode(key: brand.id,data: brand);

        for(PricePart serial in brand.materialList){
          //系列
          if(currentSelect==serial.id){
            selectPricePart=serial;
            currentType=selectPricePart.type;
          }
          serial.path="${part.id}.${brand.id}.${serial.id}";
          treeview.TreeNode serialNode=treeview.TreeNode(key: serial.id,data: serial);

          for(PricePart part in serial.materialList){
            if(currentSelect==part.id){
              selectPricePart=part;
              currentType=selectPricePart.type;
            }
            part.path="${part.id}.${brand.id}.${serial.id}.${part.id}";
            treeview.TreeNode partNode=treeview.TreeNode(key: part.id,data: part);

            serialNode.add(partNode);
          }
          brandNode.add(serialNode);
        }
        node.add(brandNode);
      }
      trees.add(node);

    }
    sampleTree=trees;

    setState(() {

    });


    if(currentType!="part"){
      pricePartController.refreshPricePart!(selectPricePart);
    }else{
      materialController.refreshPricePart!(selectPricePart);
    }


    // if(_controller!=null){
    //   var node=_controller!.elementAt(currentSelect);
    //   _controller!.expandAllChildren(node);
    // }
  }


  void showDelPart(PricePart pricePart){
    showShadDialog(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: Text('确定要删除${pricePart.name}吗?'),
        description:  Padding(
          padding: EdgeInsets.only(bottom: 8),
          child: Text(
            '点击删除将删除${pricePart.type=="type"?"分类":"品牌"}',
          ),
        ),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
          ShadButton(
            child: const Text('删除'),
            onPressed: () {
              uploadDelPart(pricePart);

            },
          ),
        ],
      ),
    );
  }

  void showDelSerial(PricePart pricePart){
    showShadDialog(
      context: context,
      builder: (context) => ShadDialog.alert(
        title: Text('确定要删除${pricePart.name}吗?'),
        description: const Padding(
          padding: EdgeInsets.only(bottom: 8),
          child: Text(
            '点击删除将删除系列',
          ),
        ),
        actions: [
          ShadButton.outline(
            child: const Text('取消'),
            onPressed: () => Navigator.of(context).pop(false),
          ),
          ShadButton(
            child: const Text('删除'),
            onPressed: () {
              uploadDelSerial(pricePart);

            },
          ),
        ],
      ),
    );
  }


  void uploadDelSerial(PricePart partData){
    var parm={
      "id":partData.id,

    };
    BaseRequest.postHttp("price/delpriceserial",parameters: parm, canTip: true, context: context, onSuccess: (data){
      bool result=BaseRequest.chekResponse(data, true);
      if(result){
        ToastUtil.showToast("删除成功");
        getAllData();
        Navigator.of(context).pop(false);
      }
    }, onError: (error){

    });
  }


  void addSerial(PriceSerial serial,PricePart partData){
    final frequency=["定频","变频"];

    List<String> fSelect=[];
    if(serial.frequency.contains("定频")){
      fSelect.add("定频");
    }
    if(serial.frequency.contains("变频")){
      fSelect.add("变频");
    }

    showShadDialog(context: context, builder: (context)=>
        ShadDialog(

            actions: [ShadButton(child: Text('确定'),onPressed: (){
              submitSerial(serial,partData);
            },)],
            child:
            ShadForm(
              key: dialogKey,
              child:
              Column(
                children: [
                  ShadInputFormField(
                    id: 'name',
                    initialValue: serial.name,
                    label: const Text('系列名称'),
                    placeholder: const Text('请输入系列名称'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入系列名称';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'code',
                    initialValue: serial.code,
                    label: const Text('部件编码'),
                    placeholder: const Text('请输入部件编码'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入部件编码';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'productSerial',
                    initialValue: serial.productSerial,
                    label: const Text('适用产品系列'),
                    placeholder: const Text('适用产品系列'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入产品系列';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'models',
                    initialValue: serial.models,
                    label: const Text('适用机型'),
                    placeholder: const Text('适用机型'),
                    validator: (v) {
                      if (v.isEmpty) {
                        return '请输入适用机型';
                      }
                      return null;
                    },
                  ),
                  ShadInputFormField(
                    id: 'compressor',
                    initialValue: serial.compressor,
                    label: const Text('压缩机'),
                    placeholder: const Text('请输入压缩机'),

                  ),



                  ShadSelectMultipleFormField<String>(
                    id: 'frequency',
                    minWidth: 480,
                    maxWidth: 480,
                    label: const Text('定/变频'),
                    initialValue: fSelect,
                    options: frequency
                        .map((item) => ShadOption(value: item, child: Text(item)))
                        .toList(),

                    placeholder: const Text('请选择'),

                    validator: (v) {
                      if (v == null||v.isEmpty) {
                        return '请选择';
                      }
                      return null;
                    },
                    selectedOptionsBuilder: (context, values) =>
                        Text(values.map((v) => v).join(', ')),


                  ),


                  ShadInputFormField(
                    id: 'remark',
                    initialValue: serial.remark,
                    label: const Text('摘要'),
                    placeholder: const Text('请输入摘要'),

                  ),
                ],
              ),)

        )
    );
  }

  void submitSerial(PriceSerial serial,PricePart partData){
    if (dialogKey.currentState!.saveAndValidate()) {
      var values= dialogKey.currentState!.value;
      var name=values["name"];
      var code=values["code"];
      var productSerial=values["productSerial"];
      var models=values["models"];
      var compressor=values["compressor"];
      var frequency=values["frequency"];
      var remark=values["remark"];
      var fSelect=frequency.map((v) => v).join(', ');

      var parm={
        "name":name,
        "id":serial.id,
        "partId":partData.id,
        "code":code,
        "productSerial":productSerial,
        "models":models,
        "compressor":compressor,
        "frequency":fSelect,
        "remark":remark

      };
      BaseRequest.postHttp("price/editpartserial",parameters: parm, canTip: true, context: context, onSuccess: (data){
        bool result=BaseRequest.chekResponse(data, true);
        if(result){
          ToastUtil.showToast("编辑成功");
          eventBus.fire(EventRefreshBase());
          Navigator.pop(context);
        }
      }, onError: (error){

      });
    }
  }

}

